<template>
  <div>
    <a-card class="card" :title="$t('productInfo')" :bordered="false">
      <a-form :form="infoForm" class="form">
        <a-row class="form-row">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :label="$t('productName')">
              <a-input
                v-decorator="[
                  'productName',
                  {
                    rules: [
                      {
                        required: true,
                        message: $ta('input|productName'),
                        whitespace: true,
                      },
                    ],
                  },
                ]"
                :placeholder="$ta('input|productName')"
              />
            </a-form-item>
          </a-col>
          <a-col
            :xl="{ span: 6, offset: 2 }"
            :lg="{ span: 8 }"
            :md="{ span: 12 }"
            :sm="24"
          >
            <a-form-item :label="$t('dataLength')">
              <a-input
                v-decorator="['dataLength']"
                :placeholder="$ta('input|dataLength')"
              />
            </a-form-item>
          </a-col>
          <a-col
            :xl="{ span: 8, offset: 2 }"
            :lg="{ span: 10 }"
            :md="{ span: 24 }"
            :sm="24"
          >
            <a-form-item :label="$t('dataBase')">
              <a-select
                :placeholder="$ta('select|dataBase')"
                v-decorator="['dataBase']"
              >  
              <a-select-option
                v-for="item in dataBaseSelectList"
                :value="item.dictValue"
                :key="item.dictLabel"
              >{{ item.dictLabel }}
              </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :label="$t('dataStartFlag')">
              <a-input
                v-decorator="[
                  'dataStartFlag',
                  {
                    rules: [
                      {
                        required: false,
                        message: $ta('input|dataStartFlag'),
                        whitespace: true,
                      },
                    ],
                  },
                ]"
                :placeholder="$ta('input|dataStartFlag')"
              />
            </a-form-item>
          </a-col>
          <a-col
            :xl="{ span: 6, offset: 2 }"
            :lg="{ span: 8 }"
            :md="{ span: 12 }"
            :sm="24"
          >
            <a-form-item :label="$t('dataEndFlag')">
              <a-input
                v-decorator="[
                  'dataEndFlag',
                  {
                    rules: [
                      {
                        required: false,
                        message: $ta('input|dataEndFlag'),
                        whitespace: true,
                      },
                    ],
                  },
                ]"
                :placeholder="$ta('input|dataEndFlag')"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card :title="$t('productData')" :bordered="false">
      <form :autoFormCreate="(form) => (this.dataForm = form)">
        <a-table
          :columns="dataColumns"
          :dataSource="dataSource"
          :pagination="false"
        >
          <template
            v-for="(col, i) in ['dataName', 'dataUnit', 'startPos', 'endPos']"
            :slot="col"
            slot-scope="text, record"
          >
            <a-input
              :key="col"
              v-if="record.editable"
              style="margin: -5px 0"
              :value="text"
              :placeholder="columns[i].title"
              @change="(e) => handleChange(e.target.value, record.key, col)"
            />
            <template v-else>{{ text }}</template>
          </template>
          <template slot="operation" slot-scope="text, record">
            <template v-if="record.editable">
              <span v-if="record.isNew">
                <a @click="saveRow(record.key)">{{ $t("add") }}</a>
                <a-divider type="vertical" />
                <a-popconfirm
                  :title="$t('deleteConfirm')"
                  @confirm="remove(record.key)"
                >
                  <a>{{ $t("delete") }}</a>
                </a-popconfirm>
              </span>
              <span v-else>
                <a @click="saveRow(record.key)">{{ $t("save") }}</a>
                <a-divider type="vertical" />
                <a @click="cancle(record.key)">{{ $t("cancel") }}</a>
              </span>
            </template>
            <span v-else>
              <a @click="toggle(record.key)">{{ $t("edit") }}</a>
              <a-divider type="vertical" />
              <a-popconfirm
                :title="$t('deleteConfirm')"
                @confirm="remove(record.key)"
              >
                <a>{{ $t("delete") }}</a>
              </a-popconfirm>
            </span>
          </template>
        </a-table>
        <a-button
          style="width: 100%; margin-top: 16px; margin-bottom: 8px"
          type="dashed"
          icon="plus"
          @click="newMember"
          >{{ $t("newMember") }}</a-button
        >
      </form>
    </a-card>
    <footer-tool-bar>
      <a-button type="primary" @click="validate" :loading="loading">{{
        $t("submit")
      }}</a-button>
    </footer-tool-bar>
  </div>
</template>

<script>
import FooterToolBar from "@/components/tool/FooterToolBar";
import { productSaveOrUpdate, productDetail } from "@/services/product";
import { dictPage } from "@/services/dict";

const columns = [
  {
    title: "解析协议名",
    dataIndex: "dataName",
    key: "dataName",
    width: "20%",
    scopedSlots: { customRender: "dataName" },
  },
  {
    title: "数据单位",
    dataIndex: "dataUnit",
    key: "dataUnit",
    width: "20%",
    scopedSlots: { customRender: "dataUnit" },
  },
  {
    title: "开始下标",
    dataIndex: "startPos",
    key: "startPos",
    width: "20%",
    scopedSlots: { customRender: "startPos" },
  },
  {
    title: "结束下标",
    dataIndex: "endPos",
    key: "endPos",
    width: "20%",
    scopedSlots: { customRender: "endPos" },
  },
  {
    title: "操作",
    key: "operation",
    scopedSlots: { customRender: "operation" },
  },
];

const dataSource = [];

export default {
  name: "ProductEditForm",
  components: { FooterToolBar },
  i18n: require("./i18n"),
  data() {
    return {
      dataBaseSelectList: [],
      loading: false,
      infoForm: this.$form.createForm(this),
      dataForm: this.$form.createForm(this),
      columns,
      dataSource,
    };
  },
  computed: {
    dataColumns() {
      return this.columns.map((column) => {
        column.title = this.$t("table." + column.key);
        return column;
      });
    },
    desc() {
      return this.$t("desc");
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.dataSource = [];

      dictPage({'entity':{'dictType':'data_base', 'enabled': 1}, 'limit': 0, 'page':0}).then((rep) => {
        for (let i = 0; i < rep.data.data.records.length; i++) {
          const element = rep.data.data.records[i];
          rep.data.data.records[i].dictValue = Number(element.dictValue)
          
        }
        this.dataBaseSelectList = rep.data.data.records;
      });


      productDetail(this.$route.params.id).then((rep) => {
        const data = rep.data.data;
        for (let i = 0; i < data.productDataList.length; i++) {
          const element = data.productDataList[i];
          this.dataSource.push({
            key: this.dataSource.length + 1,
            id: element.id,
            dataName: element.dataName,
            dataUnit: element.dataUnit,
            startPos: element.startPos,
            endPos: element.endPos,
            editable: false,
            isNew: false,
      });
          
        }
        for (let i = 0; i < this.dataSource.length; i++) {
          this.dataSource[i].key = i + 1;
          this.dataSource[i].editable = false;
          this.dataSource[i].isNew = false;
        }
        this.infoForm.setFieldsValue({
          productName: data.productName,
          dataBase: data.dataBase,
          dataStartFlag: data.dataStartFlag,
          dataEndFlag: data.dataEndFlag,
          dataLength: data.dataLength,
        });
      });
    },
    handleSubmit (e) {
      e.preventDefault()
    },
    newMember() {
      this.dataSource.push({
        key: this.dataSource.length + 1,
        dataName: "",
        dataUnit: "",
        startPos: "",
        endPos: "",
        editable: true,
        isNew: true,
      });
    },
    remove(key) {
      const newData = this.dataSource.filter((item) => item.key !== key);
      this.dataSource = newData;
    },
    saveRow(key) {
      let target = this.dataSource.filter((item) => item.key === key)[0];
      target.editable = false;
      target.isNew = false;
    },
    toggle(key) {
      let target = this.dataSource.filter((item) => item.key === key)[0];
      target.editable = !target.editable;
      console.log(target)
    },
    getRowByKey(key, newData) {
      const data = this.dataSource;
      return (newData || data).filter((item) => item.key === key)[0];
    },
    cancle(key) {
      let target = this.dataSource.filter((item) => item.key === key)[0];
      target.editable = false;
    },
    handleChange(value, key, column) {
      const newData = [...this.dataSource];
      const target = newData.filter((item) => key === item.key)[0];
      if (target) {
        target[column] = value;
        this.dataSource = newData;
      }
    },
    validate() {
      var dataData = this.dataSource.filter((item) => !item.editable);
      this.infoForm.validateFields((err, values) => {
        if (!err) {
          var infoData = values;
          var body = {
            id: this.$route.params.id,
            productName: infoData.productName,
            dataLength: infoData.dataLength,
            dataBase: infoData.dataBase,
            dataStartFlag: infoData.dataStartFlag,
            dataEndFlag: infoData.dataEndFlag,
            productDataList: dataData,
          };
          productSaveOrUpdate(body).then((rep) => {
            if (rep.data.success) {
              this.$message.success("更新产品成功");
            } else {
              this.$message.error(rep.data.msg);
            }
          });
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.card {
  margin-bottom: 24px;
}
</style>
